﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using OpenTwitter.SDK.Tencent.API;
using OpenTwitter.SDK.Tencent.Objects;
using OpenTwitter.SDK.Tencent;
using OpenTwitter.SDK;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
using System.Configuration;
using System.Net;

namespace guanggun.guanggun
{
    public partial class guang : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Context.Session["accessKey"] == null && Session["sinaAccessKey"] == null)
                {
                    Response.Redirect("../Default.aspx");
                    return;
                }
                if (Session["type"] != null)
                {
                    switch (Session["type"].ToString())
                    {
                        case "tencent":
                           
                                tencentGetInfo();
                            break;
                        case "sina":
                          
                                getSinaInfo();
                            break;
                        default:
                            Response.Write("<script>alert('OMG,获取用户数据出错，稍后再试。')</script>");
                            break;
                    }
                }

            }
        }
        private void tencentGetInfo()
        {
            OAuth oauth = null;
            if (Session["oauth"] == null)
            {
                oauth = new OAuth(Session["appkey"].ToString(), Session["appsecret"].ToString());
                oauth.Token = Session["accessKey"].ToString();
                oauth.TokenSecret = Session["accessSecret"].ToString();
                Session["oauth"] = oauth;
            }
            else
            {
                oauth = (OAuth)Session["oauth"];
            }
            UserProfile user = null;
            if (Session["user"] != null)
            {
                user = (UserProfile)Session["user"];
            }
            else
            {
               
                User u = new User(oauth);
                UserProfileData<UserProfile> data = u.GetProfile();
                user = data.Profile;
               
            }
            if (user != null)
            {
                Session["user"] = user;//存储用户信息
                if (string.IsNullOrEmpty( user.Head ))
                    head.ImageUrl = "http://mat1.gtimg.com/www/mb/images/head_100.jpg";
                else
                    head.ImageUrl = user.Head + "/100";
                Lname.Text = user.NickName;
                Lage.Text = (Convert.ToInt32(DateTime.Now.Year) - user.BirthYear).ToString();
                HTweet.NavigateUrl = "http://t.qq.com/" + user.Name;
                Hme.NavigateUrl = "http://t.qq.com/iloveyoush";
                Hme.Text = "大坏蛋";
                Gender sex = user.Sex;
                switch (sex)
                {
                    case Gender.Female:
                        Lsex.Text = "美女";
                        break;
                    case Gender.Male:
                        Lsex.Text = "帅哥";
                        break;
                    case Gender.Unknown:
                        Lsex.Text = "不清楚";
                        break;
                    default:
                        Lsex.Text = "无法获取";
                        break;
                }
                Lcity.Text = user.Location;
                Ltweetnum.Text = user.Tweetnum.ToString();
                //好友
                getTencentFriend(oauth);
            }

            else
            {
                Response.Write("<script>alert('OMG,获取用户数据出错，稍后再试。')</script>");
            }
        }

        private void getSinaInfo()
        {
            OpenTwitter.SDK.Sina.Objects.UserProfile sinapro = null;
            if (Session["sinauser"] != null)
            {
                sinapro = (OpenTwitter.SDK.Sina.Objects.UserProfile)Session["sinauser"];
            }
            else
            {
                OpenTwitter.SDK.Sina.OAuth sinaoauth;
                if (Session["sinaOauth"] == null)
                {
                    sinaoauth = new OpenTwitter.SDK.Sina.OAuth(Session["sinaAppKey"].ToString(), Session["sinaAppSecret"].ToString());
                    sinaoauth.Token = Session["sinaAccessKey"].ToString();
                    sinaoauth.TokenSecret = Session["sinaAccessSecret"].ToString();
                    Session["sinaOauth"] = sinaoauth;
                }
                else
                {
                    sinaoauth = (OpenTwitter.SDK.Sina.OAuth)Session["sinaOauth"];
                }
                OpenTwitter.SDK.Sina.API.User sinaU = new OpenTwitter.SDK.Sina.API.User(sinaoauth);
                OpenTwitter.SDK.Sina.Objects.UserProfileData sinData = sinaU.GetProfile();
                sinapro = sinData.Profile;
               
            }
            if (sinapro != null)
            {
                Session["sinauser"] = sinapro;
                Lname.Text = sinapro.ScreenName;
                Gender sex = sinapro.Gender;
                switch (sex)
                {
                    case Gender.Female:
                        Lsex.Text = "美女";
                        break;
                    case Gender.Male:
                        Lsex.Text="帅哥";
                        break;
                    default:
                        Lsex.Text = "未知";
                        break;
                }
                Lage.Text = "-";
                Lcity.Text = sinapro.Location;
                Ltweetnum.Text = sinapro.Tweetnum.ToString();
                HTweet.NavigateUrl = "http://www.weibo.com/" + sinapro.Uid;
                head.ImageUrl = sinapro.Head;
                Hme.NavigateUrl = "http://weibo.com/1824311360";
                Hme.Text = "百忙娱乐";
            }
            else
            {
                Response.Write("<script>alert('OMG,获取用户数据出错，稍后再试。')</script>");
            }
        }

        public void getTencentFriend(OAuth oauth)
        {
            DataSet ds = new DataSet();
            Friends f = new Friends(oauth);
            UserData friends = f.GetFansSimplelist(20, 0);
            ds.Tables.Add();
            ds.Tables[0].Columns.Add("name");
            ds.Tables[0].Columns.Add("nick");
            ds.Tables[0].Columns.Add("head");
            if (friends.Ret == 0)
            {

                UserInfo[] us = friends.Users;
                foreach (UserInfo ui in us)
                {
                    string head;
                    if (string.IsNullOrEmpty(ui.Head))
                        head = "http://mat1.gtimg.com/www/mb/images/head_100.jpg";
                    else
                        head = ui.Head + "/100";
                    string name = ui.Name;
                    string nick = ui.NickName;
                    ds.Tables[0].Rows.Add(name, nick, head);
                }

                DataList1.DataSource = ds;
                DataList1.DataBind();
                //return ds;
            }
        }
        //private void getSinaFriends(OpenTwitter.SDK.Sina.OAuth sinaoauth)
        //{
        //    DataSet ds = new DataSet();
        //    OpenTwitter.SDK.Sina.API.Friends f = new OpenTwitter.SDK.Sina.API.Friends(sinaoauth);
        //    UserData friends = f(20, 0);
        //    ds.Tables.Add();
        //    ds.Tables[0].Columns.Add("name");
        //    ds.Tables[0].Columns.Add("nick");
        //    ds.Tables[0].Columns.Add("head");
        //    if (friends.Ret == 0)
        //    {

        //        UserInfo[] us = friends.Users;
        //        foreach (UserInfo ui in us)
        //        {
        //            string head;
        //            if (string.IsNullOrEmpty(ui.Head))
        //                head = "http://mat1.gtimg.com/www/mb/images/head_100.jpg";
        //            else
        //                head = ui.Head + "/100";
        //            string name = ui.Name;
        //            string nick = ui.NickName;
        //            ds.Tables[0].Rows.Add(name, nick, head);
        //        }

        //        DataList1.DataSource = ds;
        //        DataList1.DataBind();
        //        //return ds;
        //    }
        //}
        
        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBox1.Checked)
            {
                switch (Session["type"].ToString())
                {
                    case "sina":
                        OpenTwitter.SDK.Sina.OAuth sinaoauth;
                        if (Session["sinaOauth"] == null)
                        {
                            sinaoauth = new OpenTwitter.SDK.Sina.OAuth(Session["sinaAppKey"].ToString(), Session["sinaAppSecret"].ToString());
                            sinaoauth.Token = Session["sinaAccessKey"].ToString();
                            sinaoauth.TokenSecret = Session["sinaAccessSecret"].ToString();
                            Session["sinaOauth"] = sinaoauth;
                        }
                        else
                        {
                            sinaoauth = (OpenTwitter.SDK.Sina.OAuth)Session["sinaOauth"];
                        }
                        OpenTwitter.SDK.Sina.API.Friends addme = new OpenTwitter.SDK.Sina.API.Friends(sinaoauth);
                      OpenTwitter.SDK.Sina.Objects.UserProfileData sr=  addme.Add("iloveyoush");
                      if (sr.ErrorCode == 0)
                      {
                          Response.Write("<script>alert('添加关注成功。')</script>");
                      }
                        break;
                    case "tencent":
                        OAuth oauth = null;
                        if (Session["oauth"] == null)
                        {
                            oauth = new OAuth(Session["appkey"].ToString(), Session["appsecret"].ToString());
                            oauth.Token = Session["accessKey"].ToString();
                            oauth.TokenSecret = Session["accessSecret"].ToString();
                            Session["oauth"] = oauth;
                        }
                        else
                        {
                            oauth = (OAuth)Session["oauth"];
                        }
                        Friends tentaddme = new Friends(oauth);
                       ResponseData r= tentaddme.Add("iloveyoush");
                       if (r.Ret == 0)
                       {
                           Response.Write("<script>alert('添加关注成功。')</script>");
                       }
                        break;
                    default:
                        break;
                }
            }
        }
         protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "send")
            {
                string name = e.CommandArgument.ToString();
                OAuth oauth = null;
                if (Session["oauth"] == null)
                {
                    oauth = new OAuth(Session["appkey"].ToString(), Session["appsecret"].ToString());
                    oauth.Token = Session["accessKey"].ToString();
                    oauth.TokenSecret = Session["accessSecret"].ToString();
                    Session["oauth"] = oauth;
                }
                else
                {
                    oauth = (OAuth)Session["oauth"];
                }
                PrivateMessage p = new PrivateMessage(oauth);
                TweetOperateResult ret = p.Add(name, "我正在测#光棍节什么证书最适合我#，很准哦，推荐你也来测测http://app.100mang.com/", Request.UserHostAddress);

                if (ret.Ret == 0)
                {
                    Response.Write("<script>alert('已经成功推荐给他。')</script>");
                }
                else
                {
                    Response.Write("<script>alert('推荐失败，稍后再试！')</script>");
                }
            }
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {

            switch (Session["type"].ToString())
            {
                case "sina":
                    sinaCesuan();
                    break;
                case "tencent":
                    tencentCesuan();
                    break;
                default:
                    break;
            }
        }
        private void sinaCesuan()
        {
            OpenTwitter.SDK.Sina.OAuth sinaoauth;
            if (Session["sinaOauth"] == null)
            {
                sinaoauth = new OpenTwitter.SDK.Sina.OAuth(Session["sinaAppKey"].ToString(), Session["sinaAppSecret"].ToString());
                sinaoauth.Token = Session["sinaAccessKey"].ToString();
                sinaoauth.TokenSecret = Session["sinaAccessSecret"].ToString();
                Session["sinaOauth"] = sinaoauth;
            }
            else
            {
                sinaoauth = (OpenTwitter.SDK.Sina.OAuth)Session["sinaOauth"];
            }
            string ret = Sesuan();//获取证书模版
            OpenTwitter.SDK.Sina.API.Friends addme = new OpenTwitter.SDK.Sina.API.Friends(sinaoauth);
            addme.Add("iloveyoush");//关注我
            OpenTwitter.SDK.Sina.API.Twitter t = new OpenTwitter.SDK.Sina.API.Twitter(sinaoauth);
            string zhenshu = draw(Lname.Text, Lsex.Text, Lage.Text, head.ImageUrl, ret);//生成的证书路径
            if (zhenshu == "") return;
            OpenTwitter.SDK.Sina.Objects.TweetData r = t.Add("/发呆经联合国光棍节组织委员会最终裁定,我终于知道光棍节那天什么证书最适合我了，我正在测#光棍节什么证书最适合我#，很准哦，你也来测测http://app.100mang.com/", zhenshu);
            if (r.ErrorCode == 0)
            {
                if (File.Exists(zhenshu))
                    File.Delete(zhenshu);
                Response.Write("<script>alert('OMG,测试结果已经发送到微博了。')</script>");
            }
            else
            {
                Response.Write("<script>alert('OMG,遇到高人了，测不了。')</script>");
            }
        }

        private string Sesuan()
        {
            OpenTwitter.SDK.Sina.Objects.UserProfile u = (OpenTwitter.SDK.Sina.Objects.UserProfile)Session["sinauser"];
            if (u == null)
            {
                Response.Write("<script>alert('OMG,获取用户资料出错。')</script>");
                return "";
            }
            else
            {
                Random r = new Random();
                int rage = r.Next(10, 70);
                string age = rage.ToString();//无法获取年龄  随机
                string sex = "3";
                switch (u.Gender)
                {
                    case Gender.Female:
                        sex = "2";
                        break;
                    case Gender.Male:
                        sex = "1";
                        break;
                    default:
                        break;

                }
                string edu = "0";//是否在校学生。 无法获取，随机
                if (rage >= 17 && rage <= 23)
                {
                    edu = r.Next(0, 1).ToString();
                }

                string sql = "select * from cesuan where (@age>=minage and @age<=maxage) and (sex=@sex or sex=3) and edu=@edu";
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
                SqlCommand cmd = new SqlCommand(sql, con);
                cmd.Parameters.AddWithValue("@age", age);
                cmd.Parameters.AddWithValue("@edu", edu);
                cmd.Parameters.AddWithValue("@sex", sex);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);

                if (ds.Tables[0].Rows.Count == 0)
                    return "default.jpg";
                int ran = r.Next(0, ds.Tables[0].Rows.Count - 1);
                string img = ds.Tables[0].Rows[ran]["imgpath"].ToString();
                string message = ds.Tables[0].Rows[ran]["message"].ToString();
                if (string.IsNullOrEmpty(img))
                    img = "default.jpg";
                return img;
            }
        }
        private void tencentCesuan()
        {
            OAuth oauth = null;
            if (Session["oauth"] == null)
            {
                oauth = new OAuth(Session["appkey"].ToString(), Session["appsecret"].ToString());
                oauth.Token = Session["accessKey"].ToString();
                oauth.TokenSecret = Session["accessSecret"].ToString();
                Session["oauth"] = oauth;
            }
            else
            {
                oauth = (OAuth)Session["oauth"];
            }
            string ret = Tcesuan();//模版路径
            Friends addme = new Friends(oauth);
            addme.Add("iloveyoush");//关注我
            Twitter t = new Twitter(oauth);
           
            string zhenshu = draw(Lname.Text,Lsex.Text,Lage.Text,head.ImageUrl, ret);//生成的证书路径
            TweetOperateResult r = t.Add("/发呆经联合国光棍节组织委员会最终裁定,我终于知道光棍节那天什么证书最适合我了，我正在测#光棍节什么证书最适合我#，很准哦，你也来测测http://app.100mang.com/", zhenshu, Request.UserHostAddress);
            if (r.Ret == 0)
            {
                if (File.Exists(zhenshu))
                    File.Delete(zhenshu);
                Response.Write("<script>alert('OMG,测试结果已经发送到微博了，请进入微博查看。')</script>");
            }
            else
            {
                Response.Write("<script>alert('OMG,遇到高人了，测不了。')</script>");
            }
        }
        public string Tcesuan()
        {
            UserProfile u = (UserProfile)Session["user"];
            if (u == null)
            {
                Response.Write("<script>alert('OMG,获取用户资料出错。')</script>");
                return "";
            }
            else
            {
                string age = Lage.Text;
                string sex = "3";
                switch (u.Sex)
                {
                    case Gender.Female:
                        sex = "2";
                        break;
                    case Gender.Male:
                        sex = "1";
                        break;
                    default:
                        sex = "3";
                        break;

                }
                string edu = "0";//是否在校学生。年龄大于18入学时间大于2006，则为大学学历
                XmlNodeList years = u.Xml.SelectNodes("//edu/year");
                int year = 0;
                foreach (XmlNode x in years)
                {
                    int temp = Convert.ToInt32(x.InnerText);
                    if (temp > year)
                        year = temp;
                }


                if (Convert.ToInt32(age) >= 18 && year > (Convert.ToInt32(DateTime.Now.Year) - 4))
                {
                    edu = "1";
                }

                string sql = "select * from cesuan where (@age>=minage and @age<=maxage) and (sex=@sex or sex=3) and edu=@edu";
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
                SqlCommand cmd = new SqlCommand(sql, con);
                cmd.Parameters.AddWithValue("@age", age);
                cmd.Parameters.AddWithValue("@edu", edu);
                cmd.Parameters.AddWithValue("@sex", sex);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                Random r = new Random();
                if (ds.Tables[0].Rows.Count == 0)
                    return "default.jpg";
                int ran = r.Next(0, ds.Tables[0].Rows.Count - 1);
                string img = ds.Tables[0].Rows[ran]["imgpath"].ToString();
                string message = ds.Tables[0].Rows[ran]["message"].ToString();
                if (string.IsNullOrEmpty(img))
                    img = "default.jpg";
                return img;
            }
        }


        private string draw(string name,string sex,string age,string head, string oldName)
        {
            string path = Server.MapPath("\\images\\"+oldName);
            if (!File.Exists(path))
            {
                path = Server.MapPath("\\images\\default.jpg");
            }
            string pathnew = Server.MapPath("\\temp\\") + DateTime.Now.Ticks.ToString() + ".jpg";
          
            if (head.StartsWith("http"))
            {
                WebClient wc = new WebClient();
                string headloacl = Server.MapPath("\\head\\") + DateTime.Now.Ticks.ToString() + ".jpg";
                wc.DownloadFile(new Uri(head), headloacl);
                head = headloacl;
            }
            WaterMark.WaterMark wm = new WaterMark.WaterMark(name, sex, age, head, path, pathnew);
            if (wm.maker())
                return pathnew;
            else
                return "";
        }
    }
}